<template>
  <el-form :model="formData" :rules="rules" ref="form" label-width="100px">
    <el-form-item label="题目内容" prop="content">
      <Editor :value.sync="formData.content"></Editor>
    </el-form-item>
    <el-form-item label="题目类型" prop="type">
      <el-radio-group v-model="formData.type">
        <el-radio :label="1">单选题</el-radio>
        <el-radio :label="2">多选题</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="选项" prop="options">
      <div style="width:580px">
        <div v-for="(option, index) in formData.options" :key="index">
          <div class="flex-x justify-between items-center gap-2 mb-2">
            <input name="id" type="hidden" :value="option.id">
            <span>{{ `选项 ${option.optionNum}` }}</span>

            <el-input v-model="option.content" style="width: 300px" placeholder="选项内容"
              @keyup.enter.native="handleOptionEnter(index)">
            </el-input>
            <span>正确答案
              <el-switch v-model="option.isAnswer" @change="(val) => handleAnswerChange(val, index)">
              </el-switch>
            </span>

            <el-button type="danger" icon="el-icon-delete" @click="removeOption(index)" circle :focusable="false"
              size="mini"></el-button>
          </div>
        </div>

        <div class="flex-x justify-between items-center gap-4 mb-2">
          <span class="flex-1"></span>
          <el-button type="primary" icon="el-icon-plus" @click="addOption" circle size="mini" />
        </div>
      </div>
    </el-form-item>

    <el-form-item label="是否公开" prop="isPublic">
      <el-switch v-model="formData.isPublic"></el-switch>
    </el-form-item>
  </el-form>
</template>

<script>
import Editor from '@/components/admin/Editor.vue';
import api from '@/common/api';

export default {
  name: 'QuestionForm',
  components: {
    Editor
  },
  props: {
    value: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formData: {},
      rules: {
        content: [
          { required: true, message: '请输入题目内容', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择题目类型', trigger: 'change' }
        ],
        options: [
          { required: true, message: '请输入选项', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value.length < 2) {
                callback(new Error('至少需要两个选项'))
              } else {
                const answers = value.filter(opt => opt.isAnswer).length
                if (this.formData.type === 1 && answers === 0) {
                  callback(new Error('单选题至少需要选择一个答案'))
                } else if (this.formData.type === 2 && answers < 2) {
                  callback(new Error('多选题至少需要选择两个答案'))
                } else {
                  callback()
                }
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        const options = ['A', 'B', 'C', 'D'].map((letter, index) => ({
          questionId: this.formData.id,
          optionNum: letter,
          content: '',
          sortOrder: index + 1,
          isAnswer: false
        }))

        this.formData = Object.assign({ options, type: 1, isPublic: true }, val)
      },
      immediate: true
    },
  },
  methods: {
    addOption() {
      const nextLetter = String.fromCharCode(65 + this.formData.options.length)
      const newOption = {
        questionId: this.formData.id,
        optionNum: nextLetter,
        content: '',
        sortOrder: this.formData.options.length + 1,
        isAnswer: false
      }
      this.formData.options.push(newOption)
    },
    removeOption(index) {      
      this.formData.options.splice(index, 1)
      this.formData.options.forEach((option, idx) => {
        option.optionNum = String.fromCharCode(65 + idx)
        option.sortOrder = idx + 1
      })
    },
    handleAnswerChange(val, index) {
      if (this.formData.type === 1 && val) {
        this.formData.options.forEach((option, i) => {
          if (i !== index) {
            option.isAnswer = false
          }
        })
      }
    },
    handleOptionEnter(index) {
      if (index === this.formData.options.length - 1) {
        if (this.formData.options[index].content.trim()) {
          this.$emit('submit')
        }
      } else {
        this.$nextTick(() => {
          const inputs = this.$el.querySelectorAll('.option-item .el-input__inner')
          if (inputs[index + 1]) {
            inputs[index + 1].focus()
          }
        })
      }
    },
    resetFields() {
      this.$refs.form.resetFields()
    },
    doSubmit(done) {
      this.$refs.form.validate(async (valid) => {
        console.log(valid)
        if (!valid) {
          done && done()
          return
        }

        try {
          await api.admin_saveQuestion(this.formData);
          this.$message.success(this.formData.id ? '更新成功' : '添加成功');
          this.$emit('success')
        } catch (error) {
          this.$message.error(this.formData.id ? '更新失败' : '添加失败');
        } finally {
          done && done()
        }
      });
    }
  }
}
</script>
